package Services

import (
	"errors"
	"github.com/gin-gonic/gin"
	"time"
	Mysql "websocket_callback/Databases"
	"websocket_callback/Models"
)

type Notify struct {
	SendType string `form:"send_type" binding:"required" json:"send_type"`
	Content  string `form:"content" binding:"required" json:"content"`
	Name     string `form:"name" json:"name"`
}

func (this *Notify) WebInsert() (data map[string]interface{},err error) {
	nowDate := time.Now()
	var id int
	switch this.SendType {
	case "login": // 登陆
		var userModel Models.User
		tx := Mysql.DB.Begin()
		// 查询是否存在
		user := userModel.Get(this.Name)
		var err1,err2 error
		// 不存在插入
		if user.Id == 0 {
			userModel.Name = this.Name
			userModel.LoginTime = nowDate
			userModel.OutTime = nowDate
			id, err1 = userModel.Insert(tx)
		} else {
			result := Mysql.DB.Model(&userModel).Where("Name = ?",this.Name).Select("LoginTime").Update("LoginTime",nowDate)
			if result.Error != nil {
				err = result.Error
				return
			}
			id = user.Id
		}
		if err1 != nil {
			err = err1
			tx.Rollback()
		} else {
			// 插入登陆日志
			var userLoginLpgModel Models.UserLoginLog
			userLoginLpgModel.UserId = id
			userLoginLpgModel.LoginTime = time.Now()
			_, err2 = userLoginLpgModel.Insert(tx)
			if err2 != nil {
				err = err2
				tx.Rollback()
			}
		}
		tx.Commit()
		data = gin.H{
			"id": id,
		}
	case "send_msg":
		//var myError helper.Error
		var UserMsg Models.UserMsg
		var User Models.User
		user := User.Get(this.Name)
		if user.Id == 0 {
			return gin.H{},errors.New("该用户不存在,不能发送消息_errors")
			//return gin.H{}, myError.NewError(-1, "该用户不存在,不能发送消息")
		}
		// 插入消息
		UserMsg.UserId = user.Id
		UserMsg.Msg = this.Content
		UserMsg.CreateTime = time.Now()
		id, err = UserMsg.Insert()
		data = gin.H{
			"id": id,
		}
	case "out":
		var User Models.User
		User.Name = this.Name
		User.OutTime = time.Now()
		user := User.Get(this.Name)
		if user.Id == 0 {
			return gin.H{}, errors.New("该用户不存在,不能发送消息_errors")
			//return gin.H{}, myError.NewError(-1, "该用户不存在,不能发送消息")
		}
		err = User.Update()
		data = gin.H{}
	}
	return
}